<?php
/**
 * Created by PhpStorm.
 * User: zhd
 * Date: 2017/12/11
 * Time: 20:15
 */

namespace controller\base;


use extend\wechat\JSSDK;
use model\ActionList;
use model\Ticket;
use model\User;
use model\WechatConfig;
use ulphp\Controller;

class Base extends Controller
{
    public $actionListData  = null;
    public $wx_id           = 0;
    public $is_vote         = false;
    public $is_vote_end     = false;
    public $is_releases     = false;
    public $is_releases_end = false;

    public function __construct()
    {
        $actionList = new ActionList();
        $actionList->where('id', input('id'));
        $actionListData       = $actionList->row();
        $this->actionListData = $actionListData;
        $this->wx_id          = $actionListData['wechat_config_id'];

//        session('openid','oBL-qwgJTrIUlCKXeOkJtQKbina0');
        if (!is_weixin()) {
            echo '请在微信打开';
            exit();
        }

        if ($_SERVER['HTTP_HOST'] == 'www.bhjuba.cn') {
            redirect(SUB_DOMAIN . $_SERVER['REQUEST_URI']);
        }
    }

    public function checkActionTime()
    {
        $actionListData = $this->actionListData;
        if (time() > strtotime($actionListData['apply_time_start'])) {
            $this->is_releases = true;
        }
        if (time() > strtotime($actionListData['apply_time_end'])) {
            $this->is_releases_end = true;
        }
        if (time() > strtotime($actionListData['vote_time_start'])) {
            $this->is_vote = true;
        }
        if (time() > strtotime($actionListData['vote_time_end'])) {
            $this->is_vote_end = true;
        }
    }

    public function header()
    {
        $this->auth();
        $actionListData = $this->actionListData;
        $this->assign('actionListData', $actionListData);
        $this->checkActionTime();

        $ticket     = new Ticket();
        $ticketData = $ticket->row(['openid' => session('openid'), 'action_id' => input('id')]);
        if (empty($ticketData)) {
            $ticket->insert([
                'action_id' => input('id'),
                'openid'    => session('openid'),
                'num'       => $actionListData['ticket'],
                'add_time'  => now()
            ]);
        } else {
            $add_time = $ticketData['add_time'];
            $today    = date("Y-m-d", time());
            if (strtotime($add_time) < strtotime($today)) {
                $ticket->update(
                    [
                        'add_time' => now(),
                        'num'      => $actionListData['ticket'],
                    ],
                    ['openid' => session('openid'), 'action_id' => input('id')]
                );
            }
        }

        $jssdk       = new JSSDK(url(), $this->wx_id);
        $signPackage = $jssdk->getSignPackage();
        $this->assign('signPackage', $signPackage);
    }

    public function auth()
    {
        if (($code = input('code')) != '' && empty(session('openid'))) {
            $wechatConfig = new WechatConfig();
            $config       = $wechatConfig->row(['id' => $this->wx_id]);
            $appid        = $config['appid'];
            $appsecret    = $config['appsecret'];

            $data = http("https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$appsecret&code=$code&grant_type=authorization_code");
            $data = json_decode($data, true);
            if (isset($data['openid'])) {
                $result = User::find(['openid' => $data['openid']]);
                if (empty($result)) {
                    $result = User::create([
                        'openid'  => $data['openid'],
                        'created' => now(),
                        'ip'      => ip()
                    ]);
                    if ($result) {
                        session('openid', $data['openid']);
                    } else {
                        echo '授权失败';
                        exit();
                    }
                } else {
                    session('openid', $data['openid']);
                }
                session('access_token', $data);
            }
        }

        if (empty(session('openid'))) {
            $wechatConfig = new WechatConfig();
            $config       = $wechatConfig->row(['id' => $this->wx_id]);
            $appid        = $config['appid'];
            $redirect_uri = urlencode(MAIN_DOMAIN . $_SERVER['REQUEST_URI']);
            redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_base&state=#wechat_redirect");
        }
    }
}